<template>
  <div class="container">
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/home/project/projectListQY' }">项目列表</el-breadcrumb-item>
            <el-breadcrumb-item>修改项目信息</el-breadcrumb-item>
        </el-breadcrumb> -->
    <div>
      <el-row class="topContent">
        <el-col :span="16" class="salaryTitle">
          <div>
            <div class="contentTop clearfix">
              <p class="fl">
                <i class="icon iconfont iconfanhui1" @click="goBack"></i>
                <span class="topProjectName" id="topProjectName">{{
                  projectName
                }}</span>
              </p>
              <p class="fl statusBox">
                <span
                  :class="[
                    startStatus,
                    {
                      greenBack: statusDesc === '已开工',
                      StartOver: statusDesc === '已竣工',
                      startStop: statusDesc === '已停工',
                      noStart: statusDesc === '未开工',
                    },
                  ]"
                  >{{ statusDesc }}</span
                >
              </p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col>
            <div class="infoTitle">项目基本信息</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    prop="projectName"
                    label="项目名称"
                    label-width="135px"
                  >
                    <el-input
                      maxlength="200"
                      v-model.trim="formData.projectName"
                      placeholder="请输入项目完整名称"
                      class="proInputWidth"
                      clearable
                      filterable
                      @blur="validProName"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="施工许可证" label-width="135px">
                    <el-input
                      maxlength="200"
                      v-model.trim="formData.license"
                      placeholder="请输入施工许可证"
                      class="proInputWidth"
                      clearable
                      filterable
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    prop="startDate"
                    label="开工日期"
                    label-width="135px"
                  >
                    <el-date-picker
                      type="date"
                      placeholder="请选择"
                      v-model="formData.startDate"
                      class="proInputWidth"
                      clearable
                      value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    prop="constructionCycle"
                    label="建设周期"
                    label-width="135px"
                  >
                    <el-input
                      v-model.trim="formData.constructionCycle"
                      placeholder="请输入时长，单位为：天"
                      class="proInputWidth"
                      clearable
                    ></el-input>
                    天
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    prop="detailAddress"
                    label="详细地址"
                    label-width="135px"
                  >
                    <el-input
                      maxlength="200"
                      v-model.trim="formData.detailAddress"
                      placeholder="请输入详细地址，并在地图上确定详细位置"
                      class="proInputWidth"
                      id="suggestId"
                      @blur="hideMap"
                      ref="inputDetailAdr"
                    ></el-input>
                    <div
                      style="
                        width: 62%;
                        height: 33px;
                        background: #fff;
                        position: absolute;
                        top: 3px;
                        left: 3px;
                        z-index: 10000;
                        opacity: 0;
                      "
                      @click="showMap"
                      v-if="isShowBox"
                    ></div>
                    <div
                      id="searchResultPanel"
                      style="
                        border: 1px solid #c0c0c0;
                        width: 150px;
                        height: auto;
                        display: none;
                      "
                    ></div>
                    <el-row class="row-padding-bottom" v-if="isShowMap">
                      <el-col :span="24" class="col-position">
                        <div
                          id="l-map"
                          style="
                            height: 300px;
                            position: absolute;
                            width: 70%;
                            z-index: 1000;
                          "
                        ></div>
                      </el-col>
                    </el-row>

                    <!-- 获取当前地址  -->
                    <div id="allmap"></div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="工资发放日"
                    prop="salaryDay"
                    label-width="135px"
                  >
                    <el-select
                      placeholder="请选择"
                      :disabled="false"
                      v-model="formData.salaryDay"
                      class="proInputWidth"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="(item, index) in daySelct"
                        :key="index"
                        :value="item.value"
                        :label="item.label"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    prop="leader"
                    label="项目负责人"
                    label-width="135px"
                  >
                    <el-input
                      v-model.trim="formData.leader"
                      placeholder="请输入项目全权负责人姓名"
                      class="proInputWidth"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    prop="leaderTel"
                    label="负责人手机号码"
                    label-width="135px"
                  >
                    <el-input
                      v-model.trim="formData.leaderTel"
                      placeholder="请输入项目全权负责人手机号码"
                      class="proInputWidth"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <div class="infoTitle">项目经理信息</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    prop="proManagerName"
                    label="姓名"
                    label-width="135px"
                  >
                    <el-input
                      maxlength="200"
                      v-model.trim="formData.proManagerName"
                      placeholder="请输入姓名"
                      class="proInputWidth"
                      clearable
                      filterable
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    prop="proManagerCard"
                    label="身份证号"
                    label-width="135px"
                  >
                    <el-input
                      v-model.trim="formData.proManagerCard"
                      placeholder="请输入身份证号码"
                      class="proInputWidth"
                      clearable
                      filterable
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    prop="proManagerTel"
                    label="手机号"
                    label-width="135px"
                  >
                    <el-input
                      v-model.trim="formData.proManagerTel"
                      placeholder="请输入手机号"
                      class="proInputWidth"
                      clearable
                      filterable
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <div class="infoTitle">合同信息</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-row>
                <el-col :span="24">
                  <div class="uploadBox">
                    <el-button round class="uploadImg">上传</el-button>
                    <span class="uploadImgState"
                      >请上传项目合同第一页以及末页（需包含项目基础信息以及合同盖章内容）即可，最多上传5张图片，要求图片格式为jpg、png，最大不超过5M</span
                    >
                    <div class="upLoadDom">
                      <form id="salaryExcelForm">
                        <input
                          type="file"
                          id="salaryExcel"
                          name="file"
                          @change="fileChange"
                        />
                      </form>
                    </div>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" v-model="formData.contractImgUrl">
                  <elementImage
                    :upLoadFile="upLoadFile"
                    :srcList="srcList"
                    :oldSrcList="oldSrcList"
                    @changeSrcList="changeSrcList"
                  ></elementImage>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row style="text-align: center; margin-top: 20px">
          <el-col :span="24">
            <!-- <el-form-item> -->
            <el-button
              class="commonBut saveBtn"
              type="primary"
              @click="saveToDetail"
              v-show="isShowUpdate"
              :loading="isSaveLoading"
              >保存</el-button
            >
            <!-- </el-form-item> -->
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'

export default {
  name: 'companyProjectInfoUpd',

  data() {
    // 验证建设周期
    var validateConCycle = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('建设周期不能为空'))
      } else {
        var ConCycle = /^\+?[1-9]\d*$/
        if (!ConCycle.test(value)) {
          callback(new Error('建设周期必须是正整数'))
        } else {
          if (value >= 36500) {
            callback(new Error('建设周期不能大于36500天'))
          } else {
            callback()
          }
        }
      }
    }
    var validAddress = (rule, value, callback) => {
      var that = this
      var address = that.formData.detailAddress.replace(/\s/g, '')
      setTimeout(function () {
        if (!that.lat || !address) {
          return callback(new Error('请输入有效地址'))
        } else {
          callback()
        }
      }, 500)
    }
    return {
      projectStatus: [],
      formData: {
        projectName: '', //项目名称
        license: '', // 施工许可证
        startDate: '', //开工日期
        constructionCycle: '', //建设周期
        detailAddress: '', //详细地址
        salaryDay: '', //工资发放日
        proManagerName: '', //项目经理姓名
        proManagerCard: '', //项目经理身份证号
        proManagerTel: '', //项目经理手机号
        practiceCertificate: '', //执业证书
        certificateNum: '', //证书编号
        contractImgUrl: [],
        leader: '',
        leaderTel: '',
      },
      projectName: '',
      formRules: {
        projectName: [
          {
            required: true,
            message: '项目名称不能为空',
            trigger: 'blur',
          },
        ],
        startDate: [
          {
            required: true,
            message: '开工日期不能为空',
            trigger: 'change',
          },
        ],
        salaryDay: [
          {
            required: true,
            message: '工资发放日不能为空',
            trigger: 'change',
          },
        ],
        constructionCycle: [
          {
            required: true,
            validator: validateConCycle,
            trigger: 'blur',
          },
        ],
        detailAddress: [
          {
            required: true,
            validator: validAddress,
            trigger: 'change',
          },
        ],
        proManagerName: [
          {
            required: true,
            message: '项目经理姓名不能为空',
            trigger: 'blur',
          },
        ],
        proManagerCard: [
          {
            required: true,
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: '请输入正确的身份证号',
            trigger: 'blur',
          },
        ],
        proManagerTel: [
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        leader: [
          {
            required: true,
            message: '项目全权负责人姓名不能为空',
            trigger: 'blur',
          },
        ],
        leaderTel: [
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
      },
      isShowMap: false, //是否显示地图
      lon: '',
      lat: '',
      LocationPoint: '',
      isShowBox: true,
      selectData: '',
      projectType: [], //工程类型
      startStatus: 'startStatus', //状态样式
      statusDesc: '',
      status: '',
      projectId: '',
      companyType: '',
      isSaveLoading: false, // 保存loading
      upLoadFile: [], //附件
      srcList: [],
      oldSrcList: [],
      isShowUpdate: '',
    }
  },
  computed: {
    daySelct() {
      var daySelct = []
      for (var i = 1; i <= 31; i++) {
        var obj = {}
        obj.value = i
        obj.label = i
        daySelct.push(obj)
      }
      return daySelct
    },
  },
  created() {
    this.projectId = this.$route.query.projectId
    this.companyType = this.$route.query.companyType
    //初始化信息
    this.getInitInfo()
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('projectList:update') > -1
  },
  mounted() {
    this.$nextTick(function () {
      this.getLocation()
    })
  },
  methods: {
    goBack() {
      this.$router.push({
        path: '/home/companyProjectManage/projectDetailQY',
        name: 'projectDetailQY',
        query: {
          projectId: this.projectId,
          companyType: this.companyType,
        },
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/project/projectListQY',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getInitInfo() {
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/initdata',
        data: {
          id: this.projectId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            var data = response.data.result
            this.lon = data.lon
            this.lat = data.lat
            this.formData.projectName = data.projectName
            this.formData.license = data.license
            this.formData.startDate = data.startDate
            this.formData.salaryDay = data.salaryDay
            this.formData.constructionCycle = data.cycle
            this.formData.detailAddress = data.address
            this.formData.proManagerName = data.managerName
            this.formData.proManagerCard = data.managerIdcard
            this.formData.proManagerTel = data.managerTel
            this.statusDesc = data.statusDesc
            this.status = data.status
            this.projectName = data.projectName
            this.upLoadFile = data.contractFiles
            this.formData.leader = data.leader //---项目负责人
            this.formData.leaderTel = data.leaderTel //---项目负责人电话
            this.$nextTick(() => {
              this.$refs.formData.clearValidate()
            })
          }
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    saveToDetail() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 保存更新
          this.isSaveLoading = true
          this.submitFormUptate()
        } else {
          return false
        }
      })
    },
    submitFormUptate() {
      var data = {
        id: this.projectId,
        lon: this.lon,
        lat: this.lat,
        projectName: this.formData.projectName,
        license: this.formData.license,
        startDate: this.formData.startDate,
        salaryDay: this.formData.salaryDay,
        cycle: this.formData.constructionCycle,
        address: this.formData.detailAddress,
        managerName: this.formData.proManagerName,
        managerIdcard: this.formData.proManagerCard,
        managerTel: this.formData.proManagerTel,
        status: this.status,
        leader: this.formData.leader,
        leaderTel: this.formData.leaderTel, //---项目负责人电话
        files: JSON.stringify(this.upLoadFile), //---项目合同附件
      }
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/cprojectedit',
        data: data,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$router.push({
              path: '/home/companyProjectManage/projectDetailQY',
              name: 'projectDetailQY',
              query: {
                projectId: this.projectId,
                companyType: this.companyType,
              },
            })
            this.$store.commit('CHANGE_SLIDER_NAME', {
              oldUrl: '/home/project/projectListQY',
              newUrl: this.$router.currentRoute.fullPath,
            })
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    getLocation() {
      var that = this
      var map = new BMap.Map('allmap')

      function myFun(result) {
        var cityName = result.name
        map.setCenter(cityName)
        that.LocationPoint = cityName
      }
      var myCity = new BMap.LocalCity()
      myCity.get(myFun)
    },
    showMap() {
      this.isShowMap = true
      this.isShowBox = false
      var addressName = this.formData.detailAddress
      this.$nextTick(function () {
        // 详细地址获取焦点
        this.$refs.inputDetailAdr.focus()
        this.initMap()
        setTimeout(function () {
          if ($('.tangram-suggestion-main').length == 1) {
            $('#suggestId').val(addressName)
          }
        }, 50)
        $('#suggestId').val(addressName)
      })
    },
    hideMap() {
      var that = this
      setTimeout(function () {
        if (that.selectData == '1') {
          that.isShowMap = true
          that.selectData = ''
          that.isShowBox = false
        } else {
          that.isShowMap = false
          that.isShowBox = true
        }
      }, 500)
    },
    initMap() {
      var that = this
      // 百度地图API功能
      function G(id) {
        return document.getElementById(id)
      }

      var map = new BMap.Map('l-map')
      if (that.formData.detailAddress) {
        that.isShowMap = true
        this.isShowBox = false

        var point = new BMap.Point(that.lon, that.lat)

        map.centerAndZoom(point, 16)

        var mk = new BMap.Marker(point)
        map.addOverlay(mk)
        map.panTo(point)
      } else {
        var myGeo = new BMap.Geocoder()
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(
          that.LocationPoint,
          function (point) {
            if (point) {
              map.centerAndZoom(point, 16)

              var mk = new BMap.Marker(point)

              map.addOverlay(mk)
              map.panTo(point)
            } else {
              // alert("您选择地址没有解析到结果!");
            }
          },
          '北京市'
        )
      }
      //增加滚轮放大缩小
      map.enableScrollWheelZoom(true)

      //增加滚轮放大缩小
      var ac = new BMap.Autocomplete({
        //建立一个自动完成的对象
        input: 'suggestId',
        location: map,
      })

      ac.addEventListener('onhighlight', function (e) {
        // that.selectData = "1";
        //鼠标放在下拉列表上的事件
        var str = ''
        var _value = e.fromitem.value
        var value = ''
        if (e.fromitem.index > -1) {
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business
        }
        str =
          'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value

        value = ''
        if (e.toitem.index > -1) {
          _value = e.toitem.value
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business
        }
        str +=
          '<br />ToItem<br />index = ' +
          e.toitem.index +
          '<br />value = ' +
          value
        G('searchResultPanel').innerHTML = str
      })

      var myValue
      ac.addEventListener('onconfirm', function (e) {
        that.selectData = '1'
        //鼠标点击下拉列表后的事件
        var _value = e.item.value
        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business
        G('searchResultPanel').innerHTML =
          'onconfirm<br />index = ' +
          e.item.index +
          '<br />myValue = ' +
          myValue
        that.formData.detailAddress = myValue
        setPlace()
      })

      function setPlace() {
        map.clearOverlays() //清除地图上所有覆盖物
        function myFun() {
          var pp = local.getResults().getPoi(0).point //获取第一个智能搜索的结果
          map.centerAndZoom(pp, 18)
          var marker = new BMap.Marker(pp)
          map.addOverlay(marker) //添加标注
          that.lon = pp.lng
          that.lat = pp.lat
          var geoc = new BMap.Geocoder()
        }
        var local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: myFun,
        })
        local.search(myValue)
      }
    },
    validProName() {
      if (this.formData.projectName) {
        this.axios({
          method: 'post',
          url: 'api-p/project/expand/validatename',
          data: {
            name: this.formData.projectName,
            id: this.projectId,
          },
        })
          .then((resp) => {
            if (resp.data.hasError) {
              this.$message({
                showClose: true,
                duration: 3000,
                message: resp.data.errorMsg,
                type: 'error',
              })
            }
          })
          .catch((resp) => {
            this.$message.error('数据获取失败')
          })
      }
    },
    fileChange() {
      var Filedata
      var file
      var fileSize
      Filedata = $('#salaryExcel').val()
      if (!Filedata) {
        return
      }
      try {
        file = $('#salaryExcel')[0].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过5M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      // 文件大小和限制类型可以通过子组件传值区分，若不适应于使用页面，可自行判断
      if (this.upLoadFile.length == 5) {
        this.$message({
          message: '最多上传5个附件',
          type: 'warning',
        })
        $('#salaryExcel').val('')
        return
      }
      if (fileSize / 1 > 1024 * 5) {
        this.$message({
          message: '最多能上传5M以内的附件',
          type: 'warning',
        })
        $('#salaryExcel').val('')
        return
      }
      if (!/\.(png|jpg|jpeg|PNG|JPG|JPEG)$/.test(Filedata)) {
        this.$message({
          message: '仅支持上传png、jpg、jpeg格式文件',
          type: 'warning',
        })
        $('#salaryExcel').val('')
        return
      }
      let that = this
      var options = {
        url: common.uploadUrl + 'api-f/files/upload',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
          that.upLoadFile.push(data)
          that.srcList.push(data.url)
          that.oldSrcList.push(data.url)
          $('#salaryExcel').val('')
        },
        error: function () {},
      }
      $('#salaryExcelForm').ajaxSubmit(options)
      return false
    },
    /**
     * @description: 改变图片地址
     */
    changeSrcList(val) {
      this.srcList = val
    },
  },
  watch: {
    'formData.detailAddress': {
      handler(newVal, oldVal) {
        if (oldVal) {
          if (newVal != oldVal) {
            this.lon = ''
            this.lat = ''
          }
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  .topContent {
    // height: 67px;
    position: relative;
    background: #e4ebf1;
    padding: 20px 24px;
    margin: 24px 24px 0 24px;
    .statusBox {
      margin-top: 6px;
    }
    .topProjectName {
      font: bold 18px Microsoft YaHei;
      color: #333;
      margin-bottom: 6px;
      line-height: 26px;
    }
    /* 开工状态 */
    .startStatus {
      padding: 2px 8px;
      color: #fff;
      font-size: 12px;
      margin-left: 10px;
      vertical-align: top;
    }
    .greenBack {
      background: #009588;
    }
    .StartOver {
      background: #657282;
    }
    .noStart {
      background: #ffc100;
    }
    .startStop {
      background: #d9544f;
    }
  }
  .mainCon {
    // background: #fff;
    // padding: 24px;
    // min-height: 730px;
    // margin: 0 24px;
    top: 198px;
    .infoTitle {
      font-size: 16px;
      padding: 16px 24px;
      background: #f5f7fb;
      margin-bottom: 24px;
      color: #333;
      font-weight: 700;
    }
    .proInputWidth {
      width: 65%;
    }
  }
  .uploadBox {
    position: relative;
    .uploadImg {
      width: 96px;
      height: 36px;
      color: #009588;
      border: 1px solid #009588;
      line-height: 10px;
    }
    .uploadImgState {
      font-size: 14px;
      color: #999999;
      margin-left: 12px;
    }
    .upLoadDom {
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0;
      input {
        width: 100px;
        height: 36px;
        cursor: pointer;
      }
    }
  }
  .imgStyle {
    padding-left: 100px;
    margin-top: 24px;
    li {
      position: relative;
      margin-right: 20px;
      margin-top: 10px;
      i {
        position: absolute;
        right: -6px;
        top: -10px;
        font-size: 20px;
      }
    }
  }
}
</style>
